package org.alicuu.mvc.route;

import org.alicuu.toolkit.StringUtil;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Danny
 * Date: 16/07/05
 * Time: 21:55
 */
public class RouteMatcher {
    private List<Route> routes;

    public RouteMatcher(List<Route> routes) {
        this.routes = routes;
    }

    public void setRoutes(List<Route> routes) {
        this.routes = routes;
    }

    public Route findRoute(String path) {
        String cleanPath = parsePath(path);
        List<Route> matchRoutes = new ArrayList<>();
        for (Route route : routes) {
            if (matchedPath(route.getPath(), cleanPath))
                matchRoutes.add(route);
        }

        // 优先匹配原则
        sortMatch(path, matchRoutes);

        return matchRoutes.size() > 0 ? matchRoutes.get(0) : null;
    }

    private void sortMatch(final String uri, List<Route> routes) {
        routes.sort((a, b) -> {
            if (b.getPath().equals(uri))
                return b.getPath().indexOf(uri);
            return -1;
        });
    }

    private boolean matchedPath(String routePath, String pathToMatch) {
        routePath = routePath.replaceAll(StringUtil.VAR_REGEXP, StringUtil.VAR_REPLACE);
        return pathToMatch.matches("(?i)" + routePath); // 不区分大小写
    }

    private String parsePath(String path) {
        path = StringUtil.fixPath(path);
        try {
            URI uri = new URI(path);
            return uri.getPath();
        } catch (URISyntaxException e) {
            return null;
        }
    }


}
